package com.zenagro.actions;

import java.util.*;

import javax.inject.*;

import org.openxava.actions.*;
import org.openxava.model.*;

public class SaveCustomAction extends ViewBaseAction  implements IChainAction
{
	
	private boolean resetAfter = true;
	private boolean refreshAfter = true; 
	@Inject HashMap mapaComun;
	
	public void execute() throws Exception {
		System.out.println("SaveCustom");
		Map values = null;		
		if (getView().isKeyEditable()) {
		//Create
		Map keyValues = MapFacade.createReturningKey(getModelName(), getView().getValues());
		
		addMessage("entity_created", getModelName());
		getView().clear(); 
		
		
		//Guardo en sesion las claves de la  entidad recien creada
		mapaComun.put(this.getView().getModelName(), keyValues);
		
		}else{
			// Modify				
			Map keyValues = getView().getKeyValues();	
			//Guardo en sesion las claves de la  entidad recien creada
			mapaComun.put(this.getView().getModelName(), keyValues);
			MapFacade.setValues(getModelName(), keyValues, getValuesToSave());
			addMessage("entity_modified", getModelName());
			if (!isResetAfter() && isRefreshAfter()) {
				getView().clear(); 
				values = MapFacade.getValues(getModelName(), keyValues, getView().getMembersNamesWithHidden());
			}
		}
		
		if (isResetAfter()) {
			getView().setKeyEditable(true);
			getView().reset();				
		}
		else {				
			getView().setKeyEditable(false);				
			if (isRefreshAfter()) getView().setValues(values); 
		}			
		resetDescriptionsCache();
	
	}

	public String getNextAction() throws Exception {
		return "subirFichero";
	}

	
	protected Map getValuesToSave() throws Exception {		
		return getView().getValues();		
	}
	
	/**
	 * If <tt>true</tt> reset the form after save, else refresh the
	 * form from database displayed the recently saved data. <p>
	 * 
	 * The default value is <tt>true</tt>.
	 */
	public boolean isResetAfter() {
		return resetAfter;
	}

	/**
	 * If <tt>true</tt> reset the form after save, else refresh the
	 * form from database displayed the recently saved data. <p>
	 * 
	 * The default value is <tt>true</tt>.
	 */
	public void setResetAfter(boolean b) {
		resetAfter = b;
	}

	/**
	 * If <tt>false</tt> after save does not refresh the
	 * form from database. <p>
	 * 
	 * It only has effect if <tt>resetAfter</tt> is <tt>false</tt>.
	 * 
	 * The default value is <tt>true</tt>.
	 * 
	 * @since 4.8
	 */	
	public boolean isRefreshAfter() {
		return refreshAfter;
	}

	/**
	 * If <tt>false</tt> after save does not refresh the
	 * form from database. <p>
	 * 
	 * It only has effect if <tt>resetAfter</tt> is <tt>false</tt>.
	 * 
	 * The default value is <tt>true</tt>.
	 * 
	 * @since 4.8
	 */		
	public void setRefreshAfter(boolean refreshAfter) {
		this.refreshAfter = refreshAfter;
	}

	public String[] getNextControllers() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	
}
